package com.doctor.windflower_doctor.activity;

import java.io.File;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.SystemApplication;
import com.doctor.windflower_doctor.actionBeen.DoctorAction;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.fragment.BaseFragment;
import com.doctor.windflower_doctor.fragment.MenuFragment;
import com.doctor.windflower_doctor.fragment.MenuFragment.SLMenuListOnItemClickListener;
import com.doctor.windflower_doctor.fragment.MyQueationFragment;
import com.doctor.windflower_doctor.fragment.MyQuestionHallFragment;
import com.doctor.windflower_doctor.fragment.UserControl;
import com.doctor.windflower_doctor.fragment.UserFragment;
import com.doctor.windflower_doctor.http.callback.HttpRequestCallBack;
import com.doctor.windflower_doctor.http.parser.impl.JsonParser;
import com.doctor.windflower_doctor.http.request.HttpRequest;
import com.doctor.windflower_doctor.http.request.HttpRequestParams;
import com.doctor.windflower_doctor.http.response.HttpResponseInfo;
import com.doctor.windflower_doctor.polling.PollingService;
import com.doctor.windflower_doctor.polling.PollingUtils;
import com.doctor.windflower_doctor.util.ActivityStack;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.util.LogUtils;
import com.doctor.windflower_doctor.util.StringUtil;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.service.XGPushService;

/**
 * <p>
 * 功能 主页
 * </p>
 * 
 * <p>
 * Copyright 北京亚普拓信息咨询服务有限公司 2014 All right reserved.
 * </p>
 * 
 * @author 皮勉 时间 2014年10月11日 下午4:11:28
 * @version 1.0 </br> 最后修改人 无
 */
public class MainActivity extends SlidingFragmentActivity implements SLMenuListOnItemClickListener, OnClickListener, Constent {

	private SlidingMenu mSlidingMenu;
	private TextView text_title, tv_screen;
	private ImageView logo;
	private ImageView right_img, right_red;
	private long exitTime;
	private FragmentManager fragmentManager;
	private BaseFragment currentFragment;
	private int currentPosition;
	private RelativeLayout right_layout;
	private int type = 0;
	public static final String ACTION_FRAGMENT_MYQUESTIONFRAGMENT = "com.doctor.windflower_doctor.activity_MyQueationFragment";
	public static final String ACTION_FRAGMENT_MYQUESTIONFRAGMENT_Q = "com.doctor.windflower_doctor.activity_MyQueationFragment_q";
	public static final String ACTION_FRAGMENT_USERFRAGMENT = "com.doctor.windflower_doctor.activity_UserFragment";
	public static final String ACTION_FRAGMENT = "com.doctor.windflower_doctor.activity";
	public static final String ACTION_NEW_REPLAY = "com.doctor.windflower_doctor.activity.QuestionOnLineActivity_go";
	public static final String ACTION_NAME = "com.doctor.windflower_doctor.activity.MainActivity";
	public static final String ACTION_NAME_OPEN_APP = "com.doctor.windflower_doctor.activity.MainActivity_open_app";
	public static final String ACTION_SYSTEM_NOTYFICATION = "com.doctor.windflower_doctor.activity.MainActivity_system_notyfication";
	public static final String ISSHOWRED = "isshowred";
	public static String action = "";
	public static MainActivity instance = null;
	public static boolean isTrue = false;
	public SharedPreferencesDB preferencesDB;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.frame_content);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
		instance = this;
		isTrue = false;
		text_title = (TextView) findViewById(R.id.text_title);
		logo = (ImageView) findViewById(R.id.logo);
		right_img = (ImageView) findViewById(R.id.right_img);
		right_img.setVisibility(View.GONE);
		right_img.setOnClickListener(this);
		right_layout = (RelativeLayout) findViewById(R.id.right_layout);
		tv_screen = (TextView) findViewById(R.id.screen);
		right_img.setVisibility(View.INVISIBLE);
		right_red = (ImageView) findViewById(R.id.iv_ti);
		logo.setOnClickListener(this);
		tv_screen.setOnClickListener(this);
		text_title.setText("我的问题");
		setBehindContentView(R.layout.frame_left_menu);
		mSlidingMenu = getSlidingMenu();
		mSlidingMenu.setMode(SlidingMenu.LEFT);// 设置左右都可以划出SlidingMenu菜单
		mSlidingMenu.setShadowDrawable(R.drawable.drawer_shadow);// 设置阴影图片
		mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width); // 设置阴影图片的宽度
		mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset); // SlidingMenu划出时主页面显示的剩余宽度
		mSlidingMenu.setFadeDegree(0.35f);
		mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		currentFragment = MyQueationFragment.getInstance(new Bundle());
		fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.replace(R.id.left_menu, new MenuFragment());
		fragmentTransaction.replace(R.id.content, currentFragment);
		fragmentTransaction.commitAllowingStateLoss();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_FRAGMENT_MYQUESTIONFRAGMENT);
		filter.addAction(ACTION_FRAGMENT_MYQUESTIONFRAGMENT_Q);
		filter.addAction(ACTION_FRAGMENT_USERFRAGMENT);
		filter.addAction(ACTION_NEW_REPLAY);
		filter.addAction(ACTION_NAME);
		filter.addAction(ACTION_NAME_OPEN_APP);
		filter.addAction(ACTION_SYSTEM_NOTYFICATION);
		filter.addAction(ISSHOWRED);
		registerReceiver(receiver, filter);


		preferencesDB = SharedPreferencesDB.getInstance(MainActivity.this);
	}

	public BroadcastReceiver receiver = new MyBroadcast();

	public class MyBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			String action = arg1.getAction();

			if (action.equals(ACTION_FRAGMENT_MYQUESTIONFRAGMENT)) {
				type = arg1.getIntExtra("type", 0);

			} else if (action.equals(ACTION_FRAGMENT_USERFRAGMENT)) {
				selectItem(3, "个人中心");
			} else if (action.equals(ACTION_NEW_REPLAY)) {
				LogUtils.e("========新回复===========" + currentFragment);
				if (currentFragment instanceof MyQueationFragment) {
					MyQueationFragment myQueationFragment = (MyQueationFragment) currentFragment;
					myQueationFragment.postSelect1(2);
				} else {
					type = 2;
					selectItem(0, "我的问题");
				}

			} else if (action.equals(ACTION_NAME_OPEN_APP)) {
				LogUtils.e("========打开问题" + "应用===========");
				startActivity(new Intent(MainActivity.this, MessageActivity.class));;

			} else if (action.equals(ACTION_NAME)) {
				startActivity(new Intent(MainActivity.this, MessageActivity.class));
			} else if (action.equals(ACTION_SYSTEM_NOTYFICATION)) {
				// LogUtils.e("========系统通知===========");
				// selectItem(3, "个人中心");
			} else if (action.equals(ACTION_FRAGMENT_MYQUESTIONFRAGMENT_Q)) {
				Intent intent = new Intent(MenuFragment.ACTION_FRAGMENT_MYQUESTIONFRAGMENT);
				intent.putExtra("type", 0);
				sendBroadcast(intent);

			}else if(action.equals(ISSHOWRED)){
				right_red.setVisibility(View.GONE);

			}
		}
	}

	public void setType(int type) {
		this.type = type;
	}

	@SuppressLint("NewApi")
	@Override
	public void selectItem(int position, String title) {
		LogUtils.e("====selectItem====position===========" + position);
		// update the main content by replacing fragments
		if (position > 0) {
			right_img.setVisibility(View.VISIBLE);
		} else {
			right_img.setVisibility(View.INVISIBLE);
		}
		BaseFragment fragment = null;
		text_title.setText(title);
		currentPosition = position;
		switch (position) {
		case 0:
			fragment = MyQueationFragment.getInstance(new Bundle());
			LogUtils.e("========type===========" + type);
			MyQueationFragment myQueationFragment = (MyQueationFragment) fragment;
			myQueationFragment.postSelect(type);
			type = 0;
			right_img.setVisibility(View.INVISIBLE);
			tv_screen.setVisibility(View.GONE);
			right_red.setVisibility(View.GONE);
			break;
		case 1:
			fragment = new MyQuestionHallFragment();
			right_layout.setVisibility(View.VISIBLE);
			tv_screen.setVisibility(View.VISIBLE);
			right_img.setVisibility(View.INVISIBLE);
			right_red.setVisibility(View.GONE);
			break;
		case 2:
			fragment = new UserControl();
			tv_screen.setVisibility(View.GONE);
			right_layout.setVisibility(View.VISIBLE);
			right_red.setVisibility(View.GONE);

			break;
		case 3:
			fragment = new UserFragment();
			right_layout.setVisibility(View.VISIBLE);
			tv_screen.setVisibility(View.GONE);
			right_img.setImageResource(R.drawable.icon_nofi);
			right_img.setVisibility(View.VISIBLE);
			getUser();
			break;
		default:
			break;
		}
		if (fragment != null) {
			FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
			if (currentFragment != null) {
				fragmentTransaction.hide(currentFragment);
			}
			if (!fragment.isAdded()) {
				fragmentTransaction.replace(R.id.content, fragment);
			} else {
				fragmentTransaction.show(fragment);
			}
			LogUtils.e("========fragment===========" + fragment);
			currentFragment = fragment;
			fragmentTransaction.commitAllowingStateLoss();
			// update selected item and title, then close the drawer
			setTitle(title);
			mSlidingMenu.showContent();
		} else {
			// error in creating fragment
			// Log.e("MainActivity", "Error in creating fragment");
		}
	}

	private void getUser() {

		HttpMethod requestMethod = HttpMethod.GET;
		String requestUrl = Constent.URL + Constent.USER_MESSAGE + "?doctorId=" + SharedPreferencesDB.getInstance(this).getDocotorId();
		HttpRequestCallBack<DoctorAction> requestCallBack = new HttpRequestCallBack<DoctorAction>(new JsonParser(), DoctorAction.class) {

			@Override
			protected void handleResult(HttpResponseInfo<DoctorAction> responseInfo) {
				// TODO Auto-generated method stub
				if (responseInfo.success != null) {
					if (responseInfo.success.success) {
						int num = responseInfo.success.data.numberOfUnreadMessage;
						if (num > 0) {
							right_red.setVisibility(View.VISIBLE);
						}
					}
				}

			}

			@Override
			protected void handleError(HttpException e, String msg) {
				// TODO Auto-generated method stub

			}
		};
		HttpRequestParams params = new HttpRequestParams(requestMethod, requestUrl, requestCallBack);
		HttpRequest.send(params);
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.logo:
			toggle();
			break;
		case R.id.screen:
			MyQuestionHallFragment fragments = (MyQuestionHallFragment) currentFragment;
			fragments.post();
			break;
		case R.id.right_img:
			switch (currentPosition) {
			case 1:
				MyQuestionHallFragment fragment = (MyQuestionHallFragment) currentFragment;
				fragment.post();
				break;
			case 2:
				UserControl userControl = (UserControl) currentFragment;
				userControl.post();
				break;
			case 3:
				
				UserFragment userFragment = (UserFragment) currentFragment;
				userFragment.post();
				break;
			}
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		LogUtils.e("====MainActivity======onDestroy========");
		super.onDestroy();
		instance = null;
		unregisterReceiver(receiver);
		PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_DOWN) {

			if ((System.currentTimeMillis() - exitTime) > 2500) {
				Toast.makeText(getApplicationContext(), "再按一次退出风信子-医生版", Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
				return true;
			} else {
				// deleteFilesByDirectory(new File(Constent.IMAGE_CARCH_PATH));
				XGPushManager.unregisterPush(MainActivity.this);
				deleteFilesByDirectory(new File(Constent.AUDIO_CARCH_PATH));
				ImageLoader.getInstance().clearDiskCache();
				ImageLoader.getInstance().clearMemoryCache();
				SystemApplication.getInstance().stopSoket();
				finish();
				ActivityStack.getInstance().finishAllActivity();
				System.exit(0);
			}
			return true;
		} else {
			return super.dispatchKeyEvent(event);
		}

	}

	private static void deleteFilesByDirectory(File directory) {
		if (directory != null && directory.exists() && directory.isDirectory()) {
			for (File item : directory.listFiles()) {
				item.delete();
			}
		}
	}

	@Override
	public void show() {
		toggle();
	}

	@Override
	protected void onStart() {
		LogUtils.e("====MainActivity======onStart========");
		initXG();
		super.onStart();

	}

	private void initXG() {
		XGPushConfig.enableDebug(this, false);
		XGPushManager.registerPush(getApplicationContext(), new XGIOperateCallback() {

			@Override
			public void onFail(Object arg0, int arg1, String arg2) {
			}

			@Override
			public void onSuccess(Object arg0, int arg1) {
				String accessToken = XGPushConfig.getToken(MainActivity.this);
				if (!StringUtil.isEmpty(accessToken)) {
					LogUtils.e("========accessToken====1===" + accessToken + "======preferencesDB.getAssessToken()======" + preferencesDB.getAssessToken());
					if (StringUtil.isEmpty(preferencesDB.getAssessToken()) || (!accessToken.equals(preferencesDB.getAssessToken()))) {
						LogUtils.e("========accessToken====2===" + accessToken);
						postToken(accessToken);
					}
				}
			}

		});
		Intent service = new Intent(getApplicationContext(), XGPushService.class);
		startService(service);
	}

	/**
	 * <p>
	 * 功能 更新token
	 * </p>
	 * 
	 * @author 皮勉 时间 2014年11月24日 下午3:57:04
	 */
	void postToken(final String accessToken) {
		// http://182.92.79.214:3002/api/user/update
		HttpMethod requestMethod = HttpMethod.POST;
		String requestUrl = URL_TOKEN_UPDATE + "user/update";
		LogUtils.e("=======requestUrl======postToken=====" + requestUrl);
		HttpRequestCallBack<DoctorAction> requestCallBack = new HttpRequestCallBack<DoctorAction>(new JsonParser(), DoctorAction.class) {

			@Override
			protected void handleResult(HttpResponseInfo<DoctorAction> responseInfo) {
				// TODO Auto-generated method stub
				LogUtils.e("=======handleResult=========1==" + responseInfo.success);
				if (responseInfo.success != null) {
					LogUtils.e("=======handleResult=======2====" + responseInfo.success.success);
					if (responseInfo.success.success) {
						Toast.makeText(MainActivity.this, "信鸽更新成功", Toast.LENGTH_SHORT).show();
						preferencesDB.setAssessToken(accessToken);
					}else{
						LogUtils.e("=============================出错了");
					}
				}

			}

			@Override
			protected void handleError(HttpException e, String msg) {
				// TODO Auto-generated method stub
				LogUtils.e("=======handleResult=========3==" + msg);
			}
		};
		HttpRequestParams params = new HttpRequestParams(requestMethod, requestUrl, requestCallBack);
		params.addBodyParameter(ACCOUNT_ID, SharedPreferencesDB.getInstance(MainActivity.this).getDocotorId());
		params.addBodyParameter(XINGE_TOKEN, accessToken);
		params.addBodyParameter(APPSECRET, "123123");
		HttpRequest.send(params);
	}

	@Override
	protected void onStop() {

		LogUtils.e("====MainActivity======onStop========");
		super.onStop();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		LogUtils.e("====MainActivity======onSaveInstanceState========");
		super.onSaveInstanceState(outState);

	}

}
